package lt.ntec.danblog.server.blog.model.objectify;

import com.google.inject.Inject;
import com.googlecode.objectify.*;
import java.util.List;
import lt.ntec.danblog.server.blog.model.Post;
import lt.ntec.danblog.server.blog.model.PostDAO;
import lt.ntec.danblog.server.core.model.objectify.ObjectifyBaseDAO;

class ObjectifyBlogPostDAO extends ObjectifyBaseDAO<Post> implements PostDAO {

    static {
        ObjectifyService.register(BlogPost.class);
    }

    @Inject
    public ObjectifyBlogPostDAO(Objectify ofy) {
        super(ofy);
    }

     @Override
    public void delete(Post entity) {
        ofy.delete(entity);
    }

    @Override
    public void delete(Long id) {
        ofy.delete(new Key<Post>(getEntityClass(), id));
    }

    @Override
    public Post getById(Long id) {
        BlogPost get;
        try {
            get = ofy.get(new Key<BlogPost>(BlogPost.class, id));
        } catch (NotFoundException ex) {
            return null;
        }
        return get;
    }

    @Override
    public List<? extends Post> getLastPosts() {
        Query<? extends Post> q = ofy.query(BlogPost.class).
                limit(10).
                order("-date");
        List<? extends Post> rlist = q.list();
        return rlist;
    }

    @Override
    public Class<BlogPost> getEntityClass() {
        return BlogPost.class;
    }

    @Override
    public List<? extends Post> getList() {
        Query<? extends Post> q = ofy.query(BlogPost.class);
        List<? extends Post> rlist = q.list();
        return rlist;
    }
    
    @Override
    public Long save(Post entity) {
        
        ofy.put(entity);
        
        return entity.getId();
    }
}
